<!DOCTYPE html>
<html>

<head>
    <title>Leaflet加载SuperMap各种图层</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.css" rel="stylesheet">
    <link href="https://iclient.supermap.io/dist/leaflet/iclient-leaflet.min.css" rel="stylesheet">
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        .container {
            display: flex;
            height: 100%;
        }
        .control-panel {
            width: 300px;
            padding: 10px;
            overflow-y: auto;
            box-shadow: 0 0 10px rgba(0,0,0,0.2);
            z-index: 1000;
            background-color: white;
        }
        .map-container {
            flex: 1;
            position: relative;
        }
        #map {
            width: 100%;
            height: 100%;
        }
        .layer-section {
            margin-bottom: 15px;
            border-bottom: 1px solid #eee;
            padding-bottom: 15px;
        }
        .layer-section h3 {
            margin-top: 10px;
            margin-bottom: 5px;
        }
        .layer-option {
            margin-bottom: 5px;
        }
        .layer-option label {
            display: inline-block;
            margin-left: 5px;
            cursor: pointer;
        }
        .layer-option input {
            cursor: pointer;
        }
        .layer-params {
            margin-left: 20px;
            margin-top: 5px;
            padding: 5px;
            background-color: #f5f5f5;
            border-radius: 3px;
            font-size: 12px;
        }
        .map-info {
            position: absolute;
            bottom: 10px;
            right: 10px;
            background: rgba(255, 255, 255, 0.8);
            padding: 5px 10px;
            border-radius: 4px;
            z-index: 1000;
            font-size: 12px;
            box-shadow: 0 0 5px rgba(0,0,0,0.2);
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="control-panel">
            <h2>SuperMap图层加载器</h2>
            
            <div class="layer-section">
                <h3>底图类型</h3>
                <div class="layer-option">
                    <input type="radio" name="baseLayerType" id="epsg4326" value="EPSG:4326" checked>
                    <label for="epsg4326">EPSG:4326 (WGS84)</label>
                </div>
                <div class="layer-option">
                    <input type="radio" name="baseLayerType" id="epsg3857" value="EPSG:3857">
                    <label for="epsg3857">EPSG:3857 (Web墨卡托)</label>
                </div>
            </div>
            
            <div class="layer-section">
                <h3>REST图层</h3>
                <div class="layer-option">
                    <input type="checkbox" id="worldRest" checked>
                    <label for="worldRest">World地图</label>
                    <div class="layer-params">
                        URL: iserver/services/map-world/rest/maps/World
                    </div>
                </div>
                <div class="layer-option">
                    <input type="checkbox" id="chinaRest">
                    <label for="chinaRest">中国地图</label>
                    <div class="layer-params">
                        URL: iserver/services/map-china400/rest/maps/China
                    </div>
                </div>
            </div>
            
            <div class="layer-section">
                <h3>WMTS图层</h3>
                <div class="layer-option">
                    <input type="checkbox" id="worldWmts">
                    <label for="worldWmts">World WMTS</label>
                    <div class="layer-params">
                        URL: iserver/services/map-world/wmts100<br>
                        图层: World<br>
                        Matrix集: Custom_World
                    </div>
                </div>
                <div class="layer-option">
                    <input type="checkbox" id="chinaWmts">
                    <label for="chinaWmts">中国 WMTS</label>
                    <div class="layer-params">
                        URL: iserver/services/map-china400/wmts100<br>
                        图层: China<br>
                        Matrix集: Custom_China
                    </div>
                </div>
            </div>
            
            
            <div class="layer-section">
                <h3>海量要素图层</h3>
                <div class="layer-option">
                    <input type="checkbox" id="vectorTile">
                    <label for="vectorTile">矢量瓦片</label>
                    <div class="layer-params">
                        URL: iserver/services/map-world/rest/maps/World/vectortile
                    </div>
                </div>
            </div>
            
            <div class="layer-section">
                <button onclick="resetMap()">重置地图</button>
                <button onclick="exportMapImage()">导出地图</button>
            </div>
        </div>
        
        <div class="map-container">
            <div id="map"></div>
            <div class="map-info" id="mapInfo">EPSG:4326 | 缩放级别: 1</div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.js"></script>
    <script src="https://iclient.supermap.io/dist/leaflet/iclient-leaflet.min.js"></script>
    <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

    <script>
        // 地图实例
        var map;
        // 图层集合
        var layers = {};
        // SuperMap服务根URL
        var baseUrl = "https://iserver.supermap.io/";
        
        // 初始化地图
        function initMap(crs) {
            // 清除之前的地图实例
            if (map) {
                map.remove();
                layers = {};
            }
            
            // 创建地图
            var mapOptions = {
                center: [39.9042, 116.4074],
                zoom: 5,
                maxZoom: 18,
                minZoom: 1,
                zoomControl: true,
                attributionControl: true
            };
            
            // 设置坐标系统
            if (crs === "EPSG:3857") {
                mapOptions.crs = L.CRS.EPSG3857;
            } else {
                mapOptions.crs = L.CRS.EPSG4326;
            }
            
            // 初始化地图
            map = L.map('map', mapOptions);
            
            // 添加比例尺
            L.control.scale({
                imperial: false,
                metric: true
            }).addTo(map);
            
            // 监听地图缩放事件
            map.on('zoomend', updateMapInfo);
            map.on('moveend', updateMapInfo);
            
            // 更新地图信息
            updateMapInfo();
            
            // 初始化选中的图层
            initLayers();
        }
        
        // 更新地图信息显示
        function updateMapInfo() {
            if (!map) return;
            var center = map.getCenter();
            var zoom = map.getZoom();
            var crs = document.querySelector('input[name="baseLayerType"]:checked').value;
            document.getElementById('mapInfo').innerHTML = 
                `${crs} | 缩放级别: ${zoom} | 中心点: [${center.lat.toFixed(4)}, ${center.lng.toFixed(4)}]`;
        }
        
        // 初始化图层
        function initLayers() {
            // 检查并添加REST图层
            if (document.getElementById('worldRest').checked) {
                addRestLayer('worldRest', 'World');
            }
            
            if (document.getElementById('chinaRest').checked) {
                addRestLayer('chinaRest', 'China');
            }
            
            // 检查并添加WMTS图层
            if (document.getElementById('worldWmts').checked) {
                addWmtsLayer('worldWmts', 'World');
            }
            
            if (document.getElementById('chinaWmts').checked) {
                addWmtsLayer('chinaWmts', 'China');
            }
            
            
            // 检查并添加矢量瓦片
            if (document.getElementById('vectorTile').checked) {
                addVectorTileLayer();
            }
        }
        
        // 添加REST图层
        function addRestLayer(id, layerName) {
            var serviceType = layerName.startsWith('World') ? 'map-world' : 'map-china400';
            var url = baseUrl + `iserver/services/${serviceType}/rest/maps/${layerName}`;
            
            // 如果图层已存在，先移除
            if (layers[id]) {
                map.removeLayer(layers[id]);
            }
            
            // 创建图层实例 - 使用正确的构造函数
            var layer = new L.supermap.TiledMapLayer(url, {
                transparent: true,
                prjCoordSys: {
                    epsgCode: document.getElementById('epsg4326').checked ? 4326 : 3857
                }
            });
            
            // 添加到地图和图层集合
            layer.addTo(map);
            layers[id] = layer;
        }
        
        // 添加WMTS图层
        function addWmtsLayer(id, layerName) {
            var serviceType = layerName === 'World' ? 'map-world' : 'map-china400';
            var url = baseUrl + `iserver/services/${serviceType}/wmts100`;
            var matrixSet = layerName === 'World' ? 'Custom_World' : 'Custom_China';
            
            // 如果图层已存在，先移除
            if (layers[id]) {
                map.removeLayer(layers[id]);
            }
            
            // 创建图层实例 - 使用正确的构造函数 WMTSLayer (大写W)
            var layer = new L.supermap.WMTSLayer(url, {
                layer: layerName,
                style: "default",
                tilematrixSet: matrixSet,
                format: "image/png",
                transparent: true
            });
            
            // 添加到地图和图层集合
            layer.addTo(map);
            layers[id] = layer;
        }
        
        // 添加矢量瓦片图层
        function addVectorTileLayer() {
            var id = 'vectorTile';
            var url = baseUrl + "iserver/services/map-world/rest/maps/World/vectortile.json";
            
            // 如果图层已存在，先移除
            if (layers[id]) {
                map.removeLayer(layers[id]);
            }
            
            try {
                // 使用正确的API: TiledVectorLayer
                var layer = new L.supermap.TiledVectorLayer(url, {
                    // 添加样式控制
                    style: {
                        polygon: {
                            fillColor: "#FADFD9",
                            fillOpacity: 0.7,
                            weight: 1,
                            color: "#F27B51"
                        },
                        line: {
                            color: "#83B7D5",
                            weight: 1
                        },
                        point: {
                            radius: 3,
                            fillColor: "#FFEA00",
                            color: "#272727",
                            weight: 0.5,
                            fillOpacity: 0.7
                        }
                    }
                });
                
                // 添加到地图和图层集合
                layer.addTo(map);
                layers[id] = layer;
            } catch (e) {
                console.error("加载矢量瓦片图层失败:", e);
                alert("矢量瓦片图层加载失败，请检查SuperMap iClient版本是否支持TiledVectorLayer。");
            }
        }
        
        // 重置地图
        function resetMap() {
            var crs = document.querySelector('input[name="baseLayerType"]:checked').value;
            initMap(crs);
        }
        
        // 导出地图为图片
        function exportMapImage() {
            html2canvas(document.getElementById('map'), {
                useCORS: true,
                allowTaint: true,
                logging: false,
                scale: 2  // 提高图像质量
            }).then(function(canvas) {
                // 创建下载链接
                var now = new Date();
                var timestamp = now.getFullYear() + 
                            ('0' + (now.getMonth() + 1)).slice(-2) + 
                            ('0' + now.getDate()).slice(-2) + '_' +
                            ('0' + now.getHours()).slice(-2) + 
                            ('0' + now.getMinutes()).slice(-2);
                var filename = 'SuperMap_Leaflet_' + timestamp + '.png';
                
                // 创建下载链接
                var link = document.createElement('a');
                var imgData = canvas.toDataURL('image/png');
                link.href = imgData;
                link.download = filename;
                
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            });
        }
        
        // 注册图层切换事件处理
        function registerLayerEvents() {
            // REST图层事件
            document.getElementById('worldRest').addEventListener('change', function() {
                if (this.checked) {
                    addRestLayer('worldRest', 'World');
                } else if (layers['worldRest']) {
                    map.removeLayer(layers['worldRest']);
                    delete layers['worldRest'];
                }
            });
            
            document.getElementById('chinaRest').addEventListener('change', function() {
                if (this.checked) {
                    addRestLayer('chinaRest', 'China');
                } else if (layers['chinaRest']) {
                    map.removeLayer(layers['chinaRest']);
                    delete layers['chinaRest'];
                }
            });
            
            // WMTS图层事件
            document.getElementById('worldWmts').addEventListener('change', function() {
                if (this.checked) {
                    addWmtsLayer('worldWmts', 'World');
                } else if (layers['worldWmts']) {
                    map.removeLayer(layers['worldWmts']);
                    delete layers['worldWmts'];
                }
            });
            
            document.getElementById('chinaWmts').addEventListener('change', function() {
                if (this.checked) {
                    addWmtsLayer('chinaWmts', 'China');
                } else if (layers['chinaWmts']) {
                    map.removeLayer(layers['chinaWmts']);
                    delete layers['chinaWmts'];
                }
            });

            
            // 矢量瓦片图层事件
            document.getElementById('vectorTile').addEventListener('change', function() {
                if (this.checked) {
                    addVectorTileLayer();
                } else if (layers['vectorTile']) {
                    map.removeLayer(layers['vectorTile']);
                    delete layers['vectorTile'];
                }
            });
            
            // 坐标系切换事件
            var crsRadios = document.querySelectorAll('input[name="baseLayerType"]');
            crsRadios.forEach(function(radio) {
                radio.addEventListener('change', function() {
                    resetMap();
                });
            });
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化地图
            initMap("EPSG:4326");
            
            // 注册图层事件
            registerLayerEvents();
        });
    </script>
</body>

</html>